//使用摄像头捕获视频，将每一帧图像保存到文件

#include <stdio.h> //perror
//open
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <unistd.h>          //close
#include <sys/ioctl.h>       //ioctl
#include <stdlib.h>          //EXIT_FAILURE
#include <linux/videodev2.h> //V4L2
#include <string.h>          //memset
#include <sys/mman.h>        //mmap

int main()
{
    //打开设备文件，需要读写权限
    int fd = open("/dev/video0", O_RDWR);
    if (fd < 0)
    {
        perror("open");
        return EXIT_FAILURE;
    }

    //获取设备能力(设备支持的操作)
    struct v4l2_capability cap;
    if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0)
    {
        perror("VIDIOC_QUERYCAP");
        return EXIT_FAILURE;
    }

    //是否支持视频捕获
    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE))
    {
        fprintf(stderr, "The device does not handle single-planar video capture.\n");
        return EXIT_FAILURE;
    }

    //是否支持串流
    if (!(cap.capabilities & V4L2_CAP_STREAMING))
    {
        fprintf(stderr, "The device does not handle frame streaming.\n");
        return EXIT_FAILURE;
    }

    //获取默认图像格式
    struct v4l2_format format;
    format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (ioctl(fd, VIDIOC_G_FMT, &format) < 0)
    {
        perror("VIDIOC_G_FMT");
        return EXIT_FAILURE;
    }

    printf("default format: %c%c%c%c %dx%d\n",
           format.fmt.pix.pixelformat & 0xff,
           format.fmt.pix.pixelformat >> 8 & 0xff,
           format.fmt.pix.pixelformat >> 16 & 0xff,
           format.fmt.pix.pixelformat >> 24 & 0xff,
           format.fmt.pix.width,
           format.fmt.pix.height);
           
    //获取一帧图像的大小
    //未压缩图像大小
    unsigned int frame_size = format.fmt.pix.bytesperline * format.fmt.pix.height;
    if (format.fmt.pix.bytesperline == 0)
    {
        //压缩图像大小
        frame_size = format.fmt.pix.sizeimage;
    }
    printf("frame size = %d bytes\n", frame_size);
    char* buffer = malloc(frame_size);
    if (!buffer)
    {
        perror("malloc");
        return EXIT_FAILURE;
    }

    //分配缓冲区（可以分配多个缓冲区多线程并行处理）
    struct v4l2_requestbuffers bufrequest;
    bufrequest.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    //缓冲区使用方式
    bufrequest.memory = V4L2_MEMORY_USERPTR;
    //缓冲区个数
    bufrequest.count = 1;

    if (ioctl(fd, VIDIOC_REQBUFS, &bufrequest) < 0)
    {
        perror("VIDIOC_REQBUFS");
        return EXIT_FAILURE;
    }

    //准备缓冲区
    struct v4l2_buffer bufferinfo;
    memset(&bufferinfo, 0, sizeof(bufferinfo));
    bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
    bufferinfo.memory = V4L2_MEMORY_USERPTR;
    bufferinfo.index = 0;
    //设置缓冲区
    bufferinfo.m.userptr = (unsigned long)buffer;
    //设置缓冲区大小
    bufferinfo.length = frame_size;

    //启动串流前需要缓冲区先入队
    if (ioctl(fd, VIDIOC_QBUF, &bufferinfo) < 0)
    {
        perror("VIDIOC_QBUF1");
        return EXIT_FAILURE;
    }

    //启动串流
    int type = bufferinfo.type;
    if (ioctl(fd, VIDIOC_STREAMON, &type) < 0)
    {
        perror("VIDIOC_STREAMON");
        return EXIT_FAILURE;
    }
    //帧数
    int frame = 0;

    while (1)
    {
        printf("frame %d\n", frame);
        //等待一帧图像捕获完成后将缓冲区出队（默认阻塞）
        if (ioctl(fd, VIDIOC_DQBUF, &bufferinfo) < 0)
        {
            perror("VIDIOC_QBUF");
            break;
        }
        //保存图像到文件
        char filename[20];

        sprintf(filename, "frame%03d.raw", frame++);

        int rawfile = open(filename, O_WRONLY | O_CREAT, 0660);
        if (rawfile < 0)
        {
            perror("open");
            break;
        }

        write(rawfile, buffer, bufferinfo.bytesused);
        close(rawfile);
        //缓冲区重新入队
        bufferinfo.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        bufferinfo.memory = V4L2_MEMORY_USERPTR;

        if (ioctl(fd, VIDIOC_QBUF, &bufferinfo) < 0)
        {
            perror("VIDIOC_QBUF2");
            break;
        }
    }

    //停止串流
    if (ioctl(fd, VIDIOC_STREAMOFF, &type) < 0)
    {
        perror("VIDIOC_STREAMOFF");
        return EXIT_FAILURE;
    }

    close(fd);
    return EXIT_SUCCESS;
}
